<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue';
import { generateNameToLevel } from '@/config/constant';
import { handleDelKey } from '@/utils';
import { tableConfig } from './config/table-config';
import {
    doDelPeriodList,
    doUpdatePeriodList,
    doGetWorkingPeriodList
} from '@/api/base/workCalendar/workingHours/index';
import addDataStore from '@/store/modules/addDataStore';
import { saveSuccess } from '@/components/base-ui/base-table/hooks/useTableAction';
import type { WorkingHours } from '@/api/base/workCalendar/workingHours/model/type';

const router = useRouter();

const { handleAddData } = addDataStore();

const tableRef = ref<TableRef>();

/**
 * @: 禁用相关
 */
const disabled = (row: WorkingHours) => row.unEditable;

/**
 * @: 新增相关
 */
const handleAdd = () => {
    handleAddData('workingHoursAddData');
    tableRef.value?.clearSelection();

    router.push('/workCalendar/workingHours/add');
};

/**
 * @: 删除相关
 */
const workingHoursIds = ref<number[]>([]); // 删除所需id
const working = ref<WorkingHours[]>([]);
const selection = (workingHours: WorkingHours[]) => {
    workingHoursIds.value = workingHours.map(item => item.id);
    working.value = workingHours;
};
const { handleDel, rowDel } = useDelRow(tableRef, workingHoursIds, doDelPeriodList);

/**
 * @: 行内编辑相关
 */
const { rowEdit } = useEditRow(tableRef, doUpdatePeriodList);
const saveRow = async (row: WorkingHours, oldRow: any) => {
    const editData = handleDelKey(row, ['edit', 'unEditable', 'btnSaveLoading']);
    const res = await rowEdit<WorkingHours[]>([editData], oldRow);
    if (!res) return;
    // 将最新数据替换备份数据
    saveSuccess(row, oldRow, tableRef);
};
</script>

<template>
    <div class="main">
        <base-table
            :id="generateNameToLevel('2')"
            ref="tableRef"
            :line-edit="true"
            :table-config="tableConfig"
            :get-data-fn="doGetWorkingPeriodList"
            :edit-disabled-fn="disabled"
            :del-disabled-fn="disabled"
            @change="saveRow"
            @del="rowDel"
            @selection-change="selection"
        >
            <template #tableHeadStart>
                <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增 </el-button>
            </template>
            <template #tableHeadEnd>
                <el-button
                    :icon="Delete"
                    class="m-r-16"
                    :disabled="!workingHoursIds.length"
                    @click="
                        handleDel(
                            `选中${workingHoursIds.length}行数据，删除后将无法恢复，确认删除？`
                        )
                    "
                >
                    删除
                </el-button>
            </template>
        </base-table>
    </div>
</template>

<style lang="scss" scoped>
@include b(main) {
    display: flex;
    flex: 1;
    flex-direction: column;
    padding: 1px 24px 16px;
}
</style>
